package com.cyf.smartCity.service.impl;

import com.cyf.activemq.service.MqService;
import com.cyf.db.bean.LocalCar;
import com.cyf.db.bean.LocalFeeGroup;
import com.cyf.db.bean.LocalPerson;
import com.cyf.db.bean.Person;
import com.cyf.db.mapper.CarMapper;
import com.cyf.db.mapper.PersonMapper;
import com.cyf.db.mapper.smartCity.LocalFeeGroupMapper;
import com.cyf.service.bean.CustomException;
import com.cyf.smartCity.bean.*;
import com.cyf.smartCity.service.PersonService;
import com.cyf.smartCity.service.SendDataService;
import com.cyf.util.DateUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.cyf.smartCity.bean.WechatBasicRsp.FAIL;
import static com.cyf.smartCity.bean.WechatBasicRsp.SUCCESS;

@Service
@Transactional
public class PersonServiceImpl implements PersonService {
    private static final Logger logger = LoggerFactory.getLogger(PersonServiceImpl.class);
    @Autowired
    private PersonMapper personMapper;
    @Autowired
    private CarMapper carMapper;
    @Autowired
    private SendDataService sendDataService;
    @Autowired
    private LocalFeeGroupMapper feeGroupMapper;
    @Autowired
    private MqService mqService;

    @Override
    public WechatParkListPersonRsp listPerson(WechatParkListPersonReq req) {
        WechatParkListPersonRsp rsp = new WechatParkListPersonRsp();
        rsp.setResult(FAIL);
        List<LocalPerson> localPersonList = personMapper.listBaseInfo(req.getParkingId(), req.getPersonName(),
                req.getPlate(), req.getPageNum() * req.getPageSize(), req.getPageSize());
        if (CollectionUtils.isNotEmpty(localPersonList)) {
            List<WechatParkListPersonRsp.Person> wechatPersonList = new ArrayList<>();
            for (LocalPerson localPerson : localPersonList) {
                WechatParkListPersonRsp.Person wechatPerson = new WechatParkListPersonRsp.Person();
                wechatPerson.setId(localPerson.getId());
                wechatPerson.setLocalPersonId(localPerson.getLocalPersonId());
                wechatPerson.setPersonName(localPerson.getName());
                wechatPerson.setPhone(localPerson.getPhone());
                List<String> plateList = carMapper.getPlateByPersonIdAndParkingId(localPerson.getLocalPersonId(), req.getParkingId());
                wechatPerson.setPlateList(plateList);
                wechatPersonList.add(wechatPerson);
            }
            rsp.setPersonList(wechatPersonList);
        }
        rsp.setResult(SUCCESS);
        return rsp;
    }

    @Override
    public WechatBasicRsp deletePerson(Integer id) {
        WechatBasicRsp rsp = new WechatBasicRsp();
        try {
            LocalPerson localPerson = personMapper.getLocalIdAndParkingIdById(id);
            if (localPerson == null) {
                rsp.setResult(FAIL);
                rsp.setStrError("未找到会员！");
                return rsp;
            }
            List<LocalCar> localCarList = carMapper.listIdAndLocalIdByPersonId(localPerson.getParkingId(), localPerson.getLocalPersonId());
           if(localCarList.size()>0){
               for (LocalCar localCar : localCarList) {
                   carMapper.delete(localCar.getId());
                   sendDataService.insert(LocalCar.class, localCar.getId(), localCar.getLocalCarId(), localPerson.getParkingId(), SendData.OPT_TYPE_DELETE);
               }
           }
            personMapper.logicDeleteById(id);
            sendDataService.insert(LocalPerson.class, id, localPerson.getLocalPersonId(), localPerson.getParkingId(), SendData.OPT_TYPE_UPDATE);
            rsp.setResult(SUCCESS);
        }catch (Exception e){
            logger.error("删除会员信息异常:{}",e.getMessage());
            rsp.setResult(FAIL);
            rsp.setStrError("删除会员信息异常！");
        }
        return rsp;
    }

    @Override
    public ApiAddUpdatePersonCarRsp addUpdatePersonCar(ApiAddUpdatePersonCarReq req) {
        ApiAddUpdatePersonCarRsp rsp = new ApiAddUpdatePersonCarRsp();
        rsp.setResult(ApiAddUpdatePersonCarRsp.FAIL);
        try {

            MqAddUpdatePersonAndCarReq mqReq = new MqAddUpdatePersonAndCarReq();
            mqReq.setPlates(req.getPlates());
            mqReq.setParkingId(req.getParkingId());
            mqReq.setPersonCode(req.getPersonId());
            mqReq.setPersonName(req.getPersonName());
            mqReq.setCarPortNum(req.getLotNumber());
            mqReq.setLocalFeegroupId(req.getFeeGroupId());
            mqReq.setLocalPersonId(req.getLocalPersonId());
            mqReq.setPhone(req.getPhone());

            if (StringUtils.isNotEmpty(req.getBeginTime())) {
                mqReq.setCreatedTime(DateUtil.convertStr2Date(req.getBeginTime(), "yyyy-MM-dd HH:mm:ss"));
            } else {
                mqReq.setCreatedTime(new Date());
            }
            if (StringUtils.isNotEmpty(req.getEndTime())) {
                mqReq.setEndTime(DateUtil.convertStr2Date(req.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
            } else {
                LocalFeeGroup localFeeGroup = feeGroupMapper.getByParkingIdAndLocalId(req.getParkingId(), req.getFeeGroupId());
                if (localFeeGroup == null) {
                    rsp.setStrError("计费规则不存在！");
                    return rsp;
                }
                if (localFeeGroup.isMonthOrYear()) {
                    mqReq.setEndTime(new Date());
                } else {
                    if (localFeeGroup.getCarValidTime() != null) {
                        mqReq.setEndTime(DateUtil.getDateAfterSeconds(new Date(), localFeeGroup.getCarValidTime() * 30 * 24 * 3600));
                    } else {
                        mqReq.setEndTime(new Date());
                    }
                }
            }

            MqAddUpdatePersonAndCarRsp mqAddUpdatePersonAndCarRsp = mqService.addUpdatePersonAndCar(mqReq);
            rsp.setLocalPersonId(mqAddUpdatePersonAndCarRsp.getLocalPersonId());
            rsp.setResult(SUCCESS);
        } catch (CustomException e) {
            rsp.setStrError(e.getMessage());
        } catch (Exception e) {
            logger.error("{}", e);
            rsp.setStrError("服务器异常！");
        }
        return rsp;
    }

    @Override
    public WechatParkGetPersonRsp getPerson(Integer id) {
        WechatParkGetPersonRsp rsp = new WechatParkGetPersonRsp();
        try {
            Person localPerson = personMapper.getById(id);
            if (localPerson == null) {
                rsp.setStrError("查找会员信息失败！");
                rsp.setResult(FAIL);
                return rsp;
            }
            rsp.setId(localPerson.getId());
            rsp.setLocalPersonId(localPerson.getLocalPersonId());
            rsp.setName(localPerson.getName());
            rsp.setPhone(localPerson.getPhone());
            rsp.setLotNumber(localPerson.getCarportnum());
            rsp.setBalance(localPerson.getBalance());

            List<LocalCar> localCarList = carMapper.listByPersonIdAndParkingId(localPerson.getLocalPersonId(), localPerson.getParkingId());
            if (CollectionUtils.isNotEmpty(localCarList)) {
                LocalCar localCarFirst = localCarList.get(0);
                if(localCarFirst.getCreatedTime()!=null){
                    rsp.setCreatedTime(DateUtil.convertDate2Str(localCarFirst.getCreatedTime(), DateUtil.FORMAT_YYYY_MM_DD_HH_MI_SS));
                }
                if(localCarFirst.getEndTime()!=null){
                    rsp.setEndTime(DateUtil.convertDate2Str(localCarFirst.getEndTime(), DateUtil.FORMAT_YYYY_MM_DD_HH_MI_SS));
                }
                Integer feeGroupId = localCarFirst.getFeeGroupId();
                rsp.setLocalFeegroupId(feeGroupId);
                rsp.setFeeGroupName(feeGroupMapper.getNameByParkingIdAndLocalId(localCarFirst.getParkingId(), localCarFirst.getFeeGroupId()));
                ArrayList<String> plateList = new ArrayList<>();
                for (LocalCar localCar : localCarList) {
                    plateList.add(localCar.getLicense());
                }
                rsp.setPlateList(plateList);
            }
            rsp.setResult(SUCCESS);
        }catch (Exception e){
            rsp.setStrError("查找会员信息异常！");
            rsp.setResult(FAIL);
        }
        return rsp;
    }

    @Override
    public WechatParkListFeeGroupRsp listFeeGroup(Integer parkingId) {
        WechatParkListFeeGroupRsp rsp = new WechatParkListFeeGroupRsp();
        try {
            List<LocalFeeGroup> localFeeGroupList = feeGroupMapper.listShowByParkingId(parkingId);
            if (CollectionUtils.isNotEmpty(localFeeGroupList)) {
                List<WechatParkListFeeGroupRsp.FeeGroupItem> list = new ArrayList<>();
                for (LocalFeeGroup localFeeGroup : localFeeGroupList) {
                    WechatParkListFeeGroupRsp.FeeGroupItem item = new WechatParkListFeeGroupRsp.FeeGroupItem();
                    item.setLocalFeegroupId(localFeeGroup.getLocalFeegroupId());
                    item.setBillingType(localFeeGroup.getBillingType());
                    item.setName(localFeeGroup.getName());
                    item.setCarValidMonth(localFeeGroup.getCarValidTime());
                    item.setDesc(localFeeGroup.parseFeeJson());
                    item.setFeeRate(localFeeGroup.getFee());
                    list.add(item);
                }
                rsp.setFeeGroupList(list);
            }
            rsp.setResult(SUCCESS);
        }catch (Exception e){
            rsp.setStrError("获取计费异常！");
            rsp.setResult(FAIL);
        }
        return rsp;
    }

    @Override
    public WechatParkPersonRechargeFormRsp personRechargeForm(WechatParkPersonRechargeFormReq req) {
        WechatParkPersonRechargeFormRsp rsp = new WechatParkPersonRechargeFormRsp();

        Integer carportNum = personMapper.getCarportNumById(req.getId());
        if (carportNum == null) {
            rsp.setResult(FAIL);
            rsp.setStrError("没有车位，无法充值！");
            return rsp;
        }

        rsp.setCarPortNum(carportNum);
        rsp.setParkingId(req.getParkingId());
        List<LocalFeeGroup> feeGroupList = feeGroupMapper.getWechatShowFeeRateByParkingIdAndType(req.getParkingId());
        if (CollectionUtils.isNotEmpty(feeGroupList)) {
            List<WechatParkPersonRechargeFormRsp.FeeGroupItem> wechatFeeGroupList = new ArrayList<>();
            for (LocalFeeGroup localFeeGroup : feeGroupList) {
                WechatParkPersonRechargeFormRsp.FeeGroupItem item = new WechatParkPersonRechargeFormRsp.FeeGroupItem();
                item.setFeeRate(localFeeGroup.getFee());
                item.setLocalFeegroupId(localFeeGroup.getLocalFeegroupId());
                item.setName(localFeeGroup.getName());
                wechatFeeGroupList.add(item);
            }
            rsp.setFeeGroupList(wechatFeeGroupList);
        }

        rsp.setResult(SUCCESS);
        return rsp;
    }
}
